package cn.lbd.nonblockingnio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

public class Client2 {

    public static void main(String[] args) {
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        SocketChannel socketChannel = null;
        try {
            socketChannel = SocketChannel.open();
            socketChannel.connect(new InetSocketAddress("127.0.0.1", 8010));
            System.out.println("Client connected....");
            while (true) {
                byte[] bytes = new byte[1024];
                System.in.read(bytes);
                byteBuffer.put(bytes);
                byteBuffer.flip();
                socketChannel.write(byteBuffer);
                byteBuffer.clear();

                int count = socketChannel.read(byteBuffer);
                if (count == -1){
                    socketChannel.close();
                    return;
                }
                byteBuffer.flip();
                byte[] bytes1 = new byte[byteBuffer.remaining()];
                byteBuffer.get(bytes1);
                byteBuffer.flip();
                System.out.println("Server："+new String(bytes1).trim());
                byteBuffer.clear();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
